#include "writer.h"

#include <QThread>
#include <QTime>
#include <QDebug>
#include <QTest>
#include <QObject>

static int randInt(int low, int high)
{
    // Random number between low and high
    return qrand() % ((high + 1) - low) + low;
}

Writer::Writer(Shelf& shelf, int cooldown, QObject* parent)
    : shelf_(shelf)
    , editTime_(cooldown)
    , QThread(parent)
{
    QTime time = QTime::currentTime();
    qsrand((uint)time.msec());
}

void Writer::run()
{
    Qt::HANDLE tid = QThread::currentThreadId();

    while(true) {
        int decision = randInt(0, 1);
        if (decision == 0) {
            // Writing new book
            int position = shelf_.tryToPlaceBook();
            if (position >= 0) {
                QTest::qSleep(editTime_);
                wrotedBooks_.push_back(position);
                qDebug() << tid << "W successfully place new book on position " << position;
            }
        } else {
            // Editing old book
            if(wrotedBooks_.empty()) {
                continue;
            }

            int bookToEdit = wrotedBooks_.at(randInt(0, wrotedBooks_.size() - 1));
            qDebug() << tid << "W want to edit " << bookToEdit;
            shelf_.takeForEdit(bookToEdit);
            qDebug() << tid << "W take for edit " << bookToEdit;
            // Edit in progress
            QTest::qSleep(editTime_);
            shelf_.returnFromEdit(bookToEdit);
            qDebug() << tid << "W returned " << bookToEdit;
        }

        QCoreApplication::processEvents();
    }
}
